
"""stub modules for network I/O"""

import pypione.net
from nose.tools import with_setup

_xmlrpclib = pypione.net.xmlrpclib
_urlfetch = pypione.net.urlfetch
def teardown_stubs():
    pypione.net.xmlrpclib = _xmlrpclib
    pypione.net.urlfetch = _urlfetch
    stub_urlfetch._response_queue[:] = []
    stub_xmlrpclib.Server._package_urls = {}
    stub_xmlrpclib.Server._release_data[:] = []
    
def add_stub_packages(packages):
    stub_xmlrpclib.Server._package_urls = packages

def with_packages(packages):
    return with_setup(lambda: add_stub_packages(packages))

class stub_xmlrpclib:
    class Server(object):
        _package_urls = []
        _release_data = []
        def __init__(self, url, transport=None):
            pass
        def package_releases(self, pkg):
            if pkg=='foobs':
                return ['1.0']
            elif pkg == 'nost':
                return ['0.1']
            elif pkg == 'multi':
                return ['0.9', '1.0']
            elif pkg == 'nosuchpackage':
                return []
            else:
                raise ValueError("unexpected: %s" % pkg)
        
        def package_urls(self, pkg, version):
            return self._package_urls[(pkg, version)]
        
        def release_data(self, pkg, version):
            return self._release_data.pop(0)

class StubFetchResponse(object):
    def __init__(self, content=None, content_was_truncated=False, status_code=200, headers={}):
        self.content = content
        self.content_was_truncated = content_was_truncated
        self.status_code = status_code
        self.headers = headers

class stub_urlfetch:
    _response_queue = []
    def fetch(self, url, payload=None, method=None, headers={}):
        return self._response_queue.pop(0)